import React, { useState } from 'react';
import EditModal from './components/edit-modal';
import { useHistory } from 'react-router-dom';
import TodoList from './components/todo-list';
import { inject } from 'mobx-react';

interface IProps {
  TodoStore: { list: [], add: (text: {}) => void, update: (key: string, text: string ) => void };
}

const List: React.FC<IProps> = (props) => {
  const { TodoStore: store } = props;
  const history = useHistory();
  const [show, setShow] = useState(false);
  const [editItem, setEditItem] = useState({ key: '', text: '', time: '' });

  // 添加按钮
  const handleAdd = (mode: number) => {
    if (mode) {
      setShow(true);
    } else {
      history.push('/addTodo');
    }
  }
  const handleCancel = () => {
    setShow(false);
    setEditItem({ key: '', text: '', time: '' });
  }

  const handleEdit = (key: string) => {
    const item: {} | undefined = store.list.find((item: { key: string }) => item.key === key);
    setEditItem(item || { key: '', text: '', time: ''});
    setShow(true);
  }

  const onChangeInput = (e: any) => {
    const prev = { ...editItem };
    prev.text = e.target.value;
    setEditItem(prev);
  }
  
  const handleConfirm = () => {
    if (!editItem.key) {
      store && store.add(editItem.text);
    } else {
      store && store.update(editItem.key, editItem.text);
    }
    handleCancel();
  }

  return (
    <div>
      <TodoList onAdd={handleAdd} onEdit={handleEdit} />
      {/* 弹窗 */}
      <EditModal
        show={show}
        formValue={editItem}
        onChangeInput={onChangeInput}
        onCancel={handleCancel}
        onConfirm={handleConfirm}
      />
    </div>
  );
}

export default inject('TodoStore')(List);
